package org.youyee.game.displayArea
{
	import flash.display.Sprite;
	
	import org.youyee.game.event.SceneEvent;
	import org.youyee.game.managers.AreaDepthManager;
	import org.youyee.game.managers.AreaManager;
	
	[Event (name="areaAdded", type="org.youyee.game.event.SceneEvent")]
	[Event (name="areaRemoved", type="org.youyee.game.event.SceneEvent")]
	
	/**
	 * 游戏场景 
	 * @author youyee
	 * 
	 */	
	public class Scene extends Sprite
	{
		private var _areaManager:AreaManager;
		private var _mode:int;
		
		/**
		 * 构造函数 
		 * @param mode 场景使用的渲染模式
		 * 
		 */		
		public function Scene(mode:int=0)
		{
			super();
			this._mode = mode;
			initManager();
		}
		
		/**
		 * 初始化管理器 
		 * 
		 */		
		protected function initManager():void
		{
			_areaManager = new AreaManager();
		}
		
		/**
		 * 添加一个区域 
		 * @param area
		 * 
		 */		
		protected function addArea(area:Area):void
		{
			var result:Boolean = _areaManager.addArea(area);
			
			if (result)
			{
				addChild(area);
				AreaDepthManager.refreshDepth(_areaManager.areas, this, this._mode);
				dispatchEvent(new SceneEvent(SceneEvent.AREA_ADDED, true));
			}
		}
		
		/**
		 * 移除区域 
		 * @param area
		 * 
		 */		
		protected function removeArea(area:Area):void
		{
			if (this._areaManager.removeArea(area))
			{
				if (area.parent)
				{
					area.parent.removeChild(area);
				}
				
				area.destroy();
				
				dispatchEvent(new SceneEvent(SceneEvent.AREA_REMOVED, true));
			}
		}
		
		/**
		 * 销毁此场景 
		 * 
		 */		
		public function destroy():void
		{
			if (_areaManager)
			{
				var areas:Vector.<Area> = _areaManager.areas;
				var len:int = areas ? areas.length : 0;
				var a:Area;
				
				for (var i:int=0; i<len; ++i)
				{
					a = areas[i];
					a.destroy();
					
					if (a.parent)
					{
						a.parent.removeChild(a);
					}
				}
				
				_areaManager.destroy();
				_areaManager = null;
			}
		}
	}
}